﻿using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Terminal;
using com.nm.Helper;
using george.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using george.Helper;
using TerminalAPI.models;

namespace TerminalAPI
{
    [Description("店铺货架明细")]
    public class ShopShelfHandler : BaseHandler
    {
        [MustLogin]
        [Description("店铺货架明细列表")]
        [ReturnType(typeof(PaperData<ShopShelfModel.ListModel>))]
        public ApiResult GetList(
           [ParamDescription("搜索关键字")] string Keys = "",
           [ParamDescription("删除标识")] int IsRemove = -1,
           [ParamDescription("页码")]int Page = 1,
           [ParamDescription("页数")]int Size = 10)
        {
            var dc = new TerminalEntities();
            var query = (from shop in dc.Tm_ShopShelf
                         join good in dc.Tm_GoodShelf on shop.SGID equals good.GSID
                         select new
                         {
                             shop,
                             good.GSCode,
                             good.GSName,
                         });
            if (!string.IsNullOrWhiteSpace(Keys))
                query = query.Where(t => t.shop.ShopCode.Contains(Keys)
                || t.shop.ShopName.Contains(Keys)
                || t.GSCode.Contains(Keys)
                || t.GSName.Contains(Keys));
            if (IsRemove == 0)
            {
                query = query.Where(r => r.shop.IsRemove == false);
            }
            else if (IsRemove == 1)
            {
                query = query.Where(r => r.shop.IsRemove == true);
            }
            var result = PaperData<ShopShelfModel.ListModel>.Create(query.Count(), Size, Page);
            result.Items = query.OrderByDescending(t => t.shop.CreateDate).Skip(result.Skip)
                          .Take(result.Limt).ToList()
                          .Select(o => new ShopShelfModel.ListModel
                          {
                              CreateDate = (DateTime)o.shop.CreateDate,
                              IsRemove = o.shop.IsRemove,
                              ShopCode = o.shop.ShopCode,
                              ShopName = o.shop.ShopName,
                              GSCode = o.GSCode,
                              GSName = o.GSName,
                              GSID = o.shop.SGID,
                              Qty = o.shop.Qty,
                              SSID = o.shop.SSID,
                              //ImageUrl = ImageHelper.GetResolveImageUrl(o.GSCode, "http")
                          }).ToList();
            return Success(result);
        }

        [MustLogin]
        [Description("店铺货架明细")]
        [ReturnType(typeof(ShopShelfModel.ListModel))]
        public ApiResult GetID(
            [ParamDescription("ID")] int ID)
        {
            var dc = new TerminalEntities();
            var query = (from shop in dc.Tm_ShopShelf
                         join good in dc.Tm_GoodShelf on shop.SGID equals good.GSID
                         where shop.SSID == ID
                         select new
                         {
                             shop,
                             good.GSCode,
                             good.GSName,
                         }).FirstOrDefault();
            var result = new ShopShelfModel.ListModel
            {
                CreateDate = (DateTime)query.shop.CreateDate,
                IsRemove = query.shop.IsRemove,
                ShopCode = query.shop.ShopCode,
                ShopName = query.shop.ShopName,
                GSCode = query.GSCode,
                GSName = query.GSName,
                GSID = query.shop.SGID,
                Qty = query.shop.Qty,
                SSID = query.shop.SSID,
                ImageUrl = ImageHelper.GetResolveImageUrl(query.GSCode, "http")
            };
            return Success(result);
        }

        [JsonType]
        [MustLogin]
        [Description("新增店铺货架明细")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Create([ParamDescription("输入参数")]ShopShelfModel.CreateModel param)
        {
            if (string.IsNullOrWhiteSpace(param.ShopCode)) return Error("店铺编号不能为空");
            if (param.Qty < 0) return Error("货架数量无效,不能小于0");
            if (param.GSID == 0) return Error("货架不能为空");
            var dc = new TerminalEntities();
            if (dc.Tm_ShopShelf.Any(t => t.ShopCode == param.ShopCode && t.SGID == param.GSID && t.IsRemove == false))
                return Error($"店铺编号【{param.ShopCode}】已存在编号为【{param.GSID}】的货架");
            var shop = new Tm_ShopShelf
            {
                CreateDate = DateTime.Now,
                IsRemove = false,
                ModifyDate = DateTime.Now,
                Operator = this.UserId,
                ShopCode = param.ShopCode,
                ShopName = param.ShopName,
                Qty = param.Qty,
                SGID = param.GSID
            };
            dc.Tm_ShopShelf.Add(shop);
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [JsonType]
        [MustLogin]
        [Description("编辑店铺货架明细")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult Modify([ParamDescription("输入参数")]ShopShelfModel.ModifyModel param)
        {
            if (string.IsNullOrWhiteSpace(param.ShopCode)) return Error("店铺编号不能为空");
            if (param.Qty < 0) return Error("货架数量无效,不能小于0");
            if (param.GSID == 0) return Error("货架不能为空");
            var dc = new TerminalEntities();
            //if (dc.Tm_ShopShelf.Any(t => t.ShopCode == param.ShopCode && t.SSID != param.SSID))
            //    return Error($"店铺名称【{param.ShopName}】已存在");
            var query = dc.Tm_ShopShelf.FirstOrDefault(t => t.SSID == param.SSID);
            if (query == null) return Error("无数据");
            if (query.Qty != param.Qty)
            {
                SysChangeLog.WriteLog(this.UserId, 1, param.ShopCode, "店铺货架数量变更-平台编辑", $"店铺：{ param.ShopName}数量从{query.Qty}变更为{param.Qty}.");
            }
            query.ModifyDate = DateTime.Now;
            query.Operator = this.UserId;
            query.ShopCode = param.ShopCode;
            query.ShopName = param.ShopName;
            query.Qty = param.Qty;
            query.SGID = param.GSID;
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [MustLogin]
        [ReturnType(typeof(int), "0-成功")]
        [Description("删除店铺货架明细")]
        public ApiResult Remove([ParamDescription("ID")]int ID)
        {
            var dc = new TerminalEntities();
            var query = dc.Tm_ShopShelf.FirstOrDefault(t => t.SSID == ID);
            if (query == null) return Error("无数据");
            query.IsRemove = true;
            try
            {
                dc.SaveChanges();
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
            return Success(0);
        }

        [MustLogin]
        [Description("店铺货架数量变更列表")]
        [ReturnType(typeof(PaperData<LogModel>))]
        public ApiResult GetLog(
           [ParamDescription("搜索关键字")] string Keys = "",
           [ParamDescription("投入使用时间")] DateTime BeginDate = default(DateTime),
           [ParamDescription("停止使用时间")] DateTime StopDate = default(DateTime),
           [ParamDescription("页码")]int Page = 1,
           [ParamDescription("页数")]int Size = 10)
        {
            var dc = new TerminalEntities();
            var query = from log in dc.vm_shelf_log select log;
            if (!string.IsNullOrWhiteSpace(Keys))
                query = query.Where(t => t.Code.Contains(Keys)
                || t.Context.Contains(Keys)
                || t.Memo.Contains(Keys));
            if (BeginDate != default(DateTime) || StopDate != default(DateTime))
            {
                if (BeginDate != default(DateTime))
                {
                    BeginDate = BeginDate.SetHour(0).SetMinute(0).SetSecond(0);
                }
                if (StopDate != default(DateTime))
                {
                    StopDate = StopDate.SetHour(23).SetMinute(59).SetSecond(59);
                }
                if (BeginDate != default(DateTime))
                    query = query.Where(o => o.OperatorDate >= BeginDate);
                if (StopDate != default(DateTime))
                    query = query.Where(o => o.OperatorDate <= StopDate);
            }
            var result = PaperData<LogModel>.Create(query.Count(), Size, Page);
            result.Items = query.OrderByDescending(t => t.OperatorDate).Skip(result.Skip)
                .Take(result.Limt).ToList()
                .Select(o => new LogModel
                {
                    OperatorDate = o.OperatorDate,
                    Memo = o.Memo,
                    Context = o.Context,
                    ID = o.ID,
                    Operator = o.UserName,
                    ShopCode = o.Code,
                    Type = o.Type
                }).ToList();
            return Success(result);
        }
    }
}
